package com.study.myupdate.util;

import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 请求工具类
 */
public class HttpUtil {
    private String mUrl;
    private OkHttpClient okHttpClient;
    private static HttpUtil httpUtil;
    private Handler mHandler;

    /**
     * 私有化构造方法
     */
    private HttpUtil() {
        okHttpClient = new OkHttpClient();
        mHandler = new Handler(Looper.getMainLooper());
    }

    public static HttpUtil build() {
        httpUtil = new HttpUtil();
        return httpUtil;
    }

    /**
     * url
     *
     * @param url
     * @return
     */
    public HttpUtil url(String url) {
        this.mUrl = url;
        return this;
    }

    /**
     * Simple Request
     */
    public void simpleCallBack(final NetWorkCallBack callBack) {
        Request request = new Request.Builder().url(mUrl).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure("请求失败");
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

                final String json = response.body().string();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (response.isSuccessful()) {
                            callBack.onSuccess(json);
                        } else {
                            callBack.onFailure("请求失败：" + response.code());
                        }
                    }
                });
            }
        });
    }

    public interface NetWorkCallBack {
        void onFailure(String msg);

        void onSuccess(String content);
    }

//    /**
//     * 下载App
//     *
//     * @param context
//     * @param saveDir
//     * @param fileName
//     * @param listener
//     */
//    public void downloadApp(final Context context, final String saveDir, final String fileName, final onDownloadListener listener) {
//        // 如果需要Token的话
//        // Request request = new Request.Builder().header("token",sp.getString("token" , "")).url(url).build();
//
//        Request request = new Request.Builder().url(mUrl).build();
//
//        okHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(@NotNull Call call, @NotNull IOException e) {
//                mHandler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        listener.onDownloadFailed("下载失败");
//                    }
//                });
//            }
//
//            @Override
//            public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {
//                mHandler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (response.isSuccessful()) {
//                            saveApp(response, context, saveDir, fileName, listener);
//                        } else {
//                            listener.onDownloadFailed("下载失败:" + response.code());
//                        }
//                    }
//                });
//            }
//        });
//    }
//
//    /**
//     * 保存App
//     */
//    private void saveApp(final Response response, Context context, final String saveDir, final String fileName, final onDownloadListener listener) {
//        InputStream is = null;
//        FileOutputStream fos = null;
//        is = response.body().byteStream();
//        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
//        File file = new File(path, fileName);
//        try {
//            fos = new FileOutputStream(file);
//            byte[] bytes = new byte[1024];
//            int len = 0;
//            //获取下载的文件的大小
//            long fileSize = response.body().contentLength();
//            LogUtil.i("文件大小:" + fileSize);
//            long sum = 0;
//            int porSize = 0;
//            while ((len = is.read(bytes)) != -1) {
//                fos.write(bytes);
//                sum += len;
//                porSize = (int) ((sum * 1.0f / fileSize) * 100);
//                Message message = mHandler.obtainMessage(1);
//                message.arg1 = porSize;
//                mHandler.sendMessage(message);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (is != null) {
//                    is.close();
//                }
//                if (fos != null) {
//                    fos.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        LogUtil.i("下载成功");
//
//        //        mHandler.post(new Runnable() {
////            @Override
////            public void run() {
////                InputStream is = null;
////                byte[] buf = new byte[2048];
////                int len = 0;
////                FileOutputStream fos = null;
////                String savePath = isExistDir(saveDir);
////                Log.i("mwb", "存储下载目录：" + savePath);
////
////                try {
////                    is = response.body().byteStream();
////                    long total = response.body().contentLength();
////
////                    File file = new File(savePath, getNameFromUrl(fileName));
////                    Log.i("mwb", "最终路径：" + file);
////                    fos = new FileOutputStream(file);
////                    long sum = 0;
////                    while ((len = is.read(buf)) != -1) {
////                        fos.write(buf, 0, len);
////                        sum += len;
////                        int progress = (int) (sum * 1.0f / total * 100);
////                        // 下载中
////                        listener.onDownloading(progress);
////                    }
////                    fos.flush();
////                    // 下载完成
////                    listener.onDownloadSuccess();
////
////                } catch (FileNotFoundException e) {
////                    e.printStackTrace();
////                } catch (IOException e) {
////                    e.printStackTrace();
////                } finally {
////                    try {
////                        if (is != null)
////                            is.close();
////                    } catch (IOException e) {
////                    }
////                    try {
////                        if (fos != null)
////                            fos.close();
////                    } catch (IOException e) {
////                    }
////                }
////            }
////        });
//
//    }
//
//    private String isExistDir(String saveDir) {
//        // 下载位置
//        File downloadFile =
//                new File(Environment.getExternalStorageDirectory().getPath() + "/download/", saveDir);
//        if (!downloadFile.mkdirs()) {
//            try {
//                downloadFile.createNewFile();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        String savePath = downloadFile.getAbsolutePath();
//        Log.i("mwb", "下载目录：" + savePath);
//        return savePath;
//    }
//
//    public String getNameFromUrl(String url) {
//        return url;
//    }
//
//    /**
//     * 下载监听器
//     */
//    public interface onDownloadListener {
//        /**
//         * 下载成功
//         */
//        void onDownloadSuccess();
//
//        /**
//         * 下载进度
//         *
//         * @param progress
//         */
//        void onDownloading(int progress);
//
//        /**
//         * 下载失败
//         */
//        void onDownloadFailed(String msg);
//    }

}
